package jsp;

import util.CookieUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * @author 石小俊
 * @date 2023年10月24日 11:24
 * 用户登录
 * 当用户登录时判断用户输入的用户名与密码是否正确
 * 如果正确
 *  将正确的用户名与密码保存到cookie中,保存一天
 *  且页面跳转到主页main.jsp,在主页中展示欢迎您:xxx,xxx表示具体登录的用户的用户名
 * 如果不正确
 *  则页面仍然回到登录页面login.jsp
 *  且在页面中出现错误提示:用户名或密码错误
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取表单中用户输入的数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        String url = "jdbc:mysql://127.0.0.1:3306/web?useUnicode=true&characterEncoding=utf-8";
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url,"root","");
            String sql = new StringBuffer()
                    .append(" select id,username,password,phone,address ")
                    .append(" from t_user ")
                    .append(" where username = ? ")
                    .append(" and password = ? ")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setString(1,username);
            ps.setString(2,password);
            rs = ps.executeQuery();
            if(rs.next()){
                // 将正确的用户名与密码保存到Cookie中
                CookieUtil.addCookie("username",username,response);
                CookieUtil.addCookie("password",password,response);
                // 页面跳转
                response.sendRedirect(request.getContextPath()+"/jsp/main.jsp");
                return;
            }
            request.setAttribute("loginMsg","用户名或密码错误");
            request.getRequestDispatcher("/jsp/login.jsp").forward(request,response);
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("loginMsg","服务器内部异常");
            request.getRequestDispatcher("/jsp/login.jsp").forward(request,response);
        }
    }
}
